﻿using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace YuFeng.Web.Filters
{
    public class NormalAuthFilter : ActionFilterAttribute, IAuthenticationFilter
    {
        
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                                        || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

            if (skipAuthorization)
            {
                return;
            }
            // 若用户未登陆，则报未验证错误。前端ajax请求和FormAuth会处理此异常
            if (!SessionContext.IsAuthenticated)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    // For an Ajax request, just end the request 
                    filterContext.HttpContext.Response.StatusCode = 401;
                    //filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                    filterContext.HttpContext.Response.End();
                }
                else
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                    if (HttpContext.Current.Request.Url != null)
                        filterContext.RouteData.Values.Add("returnUrl", HttpContext.Current.Request.Url.AbsoluteUri);
                }
                return;
            }
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
        }
    }
}